package cn.jx.asc.common.handler;


import cn.jx.asc.common.enums.ResultStatus;
import cn.jx.asc.common.response.Result;
import cn.jx.asc.common.response.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

@Slf4j
@SuppressWarnings("all")
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
    public Result handler(MethodArgumentTypeMismatchException e){
        log.error("全局异常捕获 ---> [MethodArgumentTypeMismatchException]: {}", e.getMessage());
        return ResultUtils.resultWithoutData(ResultStatus.PARAM_ERROR);
    }

    @ExceptionHandler(value = AuthorizationException.class)
    public Result handler(AuthorizationException e){
        log.error("运行时异常[AuthorizationException]: {}", e.getMessage());
        return ResultUtils.resultWithoutData(ResultStatus.VISITED_FORBID);
    }

    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public Result handler(HttpMessageNotReadableException e){
        log.error("参数异常[HttpMessageNotReadableException]: {}", e.getMessage());
        return ResultUtils.resultWithoutData(ResultStatus.PARAM_ERROR);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e){
        log.error("实体校验异常[RuntimeException]: {}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return ResultUtils.resultWithoutData(ResultStatus.ENETITY_FAILED, objectError.getDefaultMessage());
    }

    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public Result handler(HttpRequestMethodNotSupportedException e){
        log.error("请求方式异常[HttpRequestMethodNotSupportedException]: {}", e.getMessage());
        return ResultUtils.resultWithoutData(ResultStatus.METHOD_NOT_SUPPERED);
    }

    // 其他异常处理
    @ExceptionHandler(value = Exception.class)
    public Result handler(Exception e){
        log.error("系统异常[Exception]: {}", e.getMessage());
        return ResultUtils.resultWithoutData(ResultStatus.SYSTEM_ERROR);
    }
}
